class_name ManualControllerComponent
extends EntityControllerComponent

@onready var fsm: FSM = %FSM
var cur_speed = 0

func set_target_vel(delta:float):
	var target_dir:Vector2 = Input.get_vector("MoveLeft","MoveRight","MoveUp","MoveDown")
	if GameManager.get_cur_game_state() != GameEnum.GameState.Gaming:
		target_dir = Vector2.ZERO
	if target_dir.length() <= 0.01 and cur_speed > 0:
		cur_speed = clamp(cur_speed - cur_entity.get_entity_data().speed_acc * delta,0,cur_entity.get_entity_data().max_speed)
		target_vel = cur_speed * target_vel.normalized() * cur_entity.get_entity_data().move_speed_scale
	elif target_dir.length() > 0.01:
		cur_speed = clamp(cur_speed + cur_entity.get_entity_data().speed_acc * delta * target_dir.length(),0,cur_entity.get_entity_data().max_speed)
		target_vel = cur_speed * target_dir * cur_entity.get_entity_data().move_speed_scale
func translate_state(state_name:String):
	fsm.translate_state_by_state_name(state_name)
func set_expression_property(name:StringName,value):
	fsm.set_expression_property(name,value)
func detect_action_keys():
	for action in InputMap.get_actions():
		# 去掉内置动作
		if action.begins_with("ui_") or action.begins_with("UI_"):
			continue
		if Input.is_action_just_pressed(action):
			var key_action = GameEnum.KeyAction.get(action)
			press_key_action(key_action)
		elif Input.is_action_just_released(action):
			var key_action = GameEnum.KeyAction.get(action)
			release_key_action(key_action)
		else:
			if Input.is_action_pressed(action):
				var key_action = GameEnum.KeyAction.get(action)
				stay_key_action(key_action)
			else:
				var key_action = GameEnum.KeyAction.get(action)
				idle_key_action(key_action)

func flip():
	var target_dir = get_global_mouse_position() - cur_entity.global_position
	if (target_dir.x > 0.001 and cur_entity.scale.y < 0) or (target_dir.x < -0.001 and cur_entity.scale.y > 0):
		cur_entity.apply_scale(Vector2(-1,1))
func init_component(entity):
	super.init_component(entity)
	fsm.init_fsm(self)

func _process(delta: float) -> void:
	if cur_entity:
		super._process(delta)
		cur_entity.velocity = get_target_vel()
		cur_entity.move_and_slide()
		if cur_entity.velocity.length()>0.01:
			translate_state("Run")
		else:
			translate_state("Idle")
